#include "mainwidget.h"
#include "./ui_mainwidget.h"
#include <QPushButton>
#include <QFile>
#include <QDebug>
#include <QtConcurrent>
#include <QFuture>

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);

    initControl();
    initSqlConnection();
    initSignalSlot();
    initStyleSheet();
}

bool MainWidget::isUserValid(const QString &username, const QString &passwd, const QString &id, const int& flag)
{
    QVariantMap userInfo;
    if(flag == 0) userInfo = doctor_management->GetInfo(id);
    else userInfo = patient_management->GetInfo(id);

    QString tmp_name = userInfo.value("username").toString();
    QString tmp_passwd = userInfo.value("password").toString();

    // LOG_DEBUG() << "name: " << tmp_name << " passwd: " << tmp_passwd;

    return tmp_name == username && tmp_passwd == passwd;
}

void MainWidget::login_btn_clicked()
{
    QString username = ui->name_ld->text();
    QString passwd = ui->passwd_ld->text();
    QString identity = ui->doctor_rbtn->isChecked() ? "doctor" : "patient";

    if (username.isEmpty() || passwd.isEmpty() || identity.isEmpty()) {
        Config::popMessageBox("WARNING", "必要消息未填写", "warning");
        return;
    }

    // LOG_DEBUG() << "identity : " << identity;

    QJsonObject userInfo;
    userInfo["username"] = username;
    userInfo["password"] = passwd;

    QString d_id = doctor_management->GetIdByName(username);
    QString p_id = patient_management->GetIdByName(username);

    bool loginSuccess = false;
    if (identity == "doctor") {
        if (isUserValid(username, passwd, d_id, 0)) {
            loginSuccess = true;
        } else {
            Config::popMessageBox("ERROR", "医生用户名或密码错误", "error");
            return;
        }
    } else if (identity == "patient") {
        if (isUserValid(username, passwd, p_id, 1)) {
            loginSuccess = true;
        } else {
            Config::popMessageBox("ERROR", "患者用户名或密码错误", "error");
            return;
        }
    }

    if (loginSuccess) {
        Config::popMessageBox("SUCCESS", "登录成功", "ok");

        if (identity == "doctor") {
            // 使用 QtConcurrent 创建医生窗口
            QFuture<void> future = QtConcurrent::run([=]() {
                Widget_doctor* widget_doctor = new Widget_doctor(nullptr, d_id, doctor_management, patient_management,
                                                                  appointment_management, advice_management, prescription_management,
                                                                  medicalRecord_management);
                connect(widget_doctor, &Widget_doctor::requestChatClient, this, &MainWidget::handleDoctorChatRequest);
                widget_doctor->show();
                // 事件循环，确保窗口保持打开
                QEventLoop eventLoop;
                eventLoop.exec();
            });
        } else if (identity == "patient") {
            // 使用 QtConcurrent 创建患者窗口
            QFuture<void> future = QtConcurrent::run([=]() {
                Widget_patient* widget_patient = new Widget_patient(nullptr, p_id, doctor_management, patient_management,
                                                                    appointment_management, advice_management, prescription_management,
                                                                    medicalRecord_management);
                connect(widget_patient, &Widget_patient::requestChatClient, this, &MainWidget::handlePatientChatRequest);
                widget_patient->show();
                // 事件循环，确保窗口保持打开
                QEventLoop eventLoop;
                eventLoop.exec();
            });
        }
    }
}

void MainWidget::register_btn_clicked()
{
    Register* reg = new Register();
    reg->setAttribute(Qt::WA_DeleteOnClose);
    reg->setWindowModality(Qt::ApplicationModal);
    reg->show();
}

void MainWidget::initSignalSlot()
{
    connect(ui->login_btn, &QPushButton::clicked, this, &MainWidget::login_btn_clicked);
    connect(ui->register_btn, &QPushButton::clicked, this, &MainWidget::register_btn_clicked);
}

void MainWidget::initStyleSheet()
{
    QFile file("./StyleSheet/MainWidget.qss");
    if (file.open(QFile::ReadOnly)) {
        QString styleSheet = file.readAll();
        this->setStyleSheet(styleSheet); // 应用样式表
        file.close();
    } else {
        qWarning() << "Unable to open style sheet file:" << file.errorString();
    }
}

void MainWidget::initSqlConnection()
{
    sql_management = new SQLManagement(g_host, g_user, g_passwd, g_database);
    doctor_management = new DoctorManagement(sql_management);
    patient_management = new PatientManagement(sql_management);
    appointment_management = new AppointmentManagement(sql_management);
    advice_management = new AdviceManagement(sql_management);
    prescription_management = new PrescriptionManagement(sql_management);
    medicalRecord_management = new MedicalRecordManagement(sql_management);
}

void MainWidget::initControl()
{
    ui->passwd_ld->setEchoMode(QLineEdit::Password);
}

MainWidget::~MainWidget()
{
    delete ui;
}

void MainWidget::handleDoctorChatRequest() {
    // 处理来自 Widget_doctor 发送的信号，展示聊天窗口
    ChatWidget *chatWidget = new ChatWidget("doctor");
    chatWidget->show();
}

void MainWidget::handlePatientChatRequest()
{
    ChatWidget *chatWidget = new ChatWidget("patient");
    chatWidget->show();
}
